﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Mail;
using Aandelendelen.Db;
using Aandelendelen.Payment;

namespace Aandelendelen.Controls
{
	public partial class IdealPaymentControl : AuthenticationRequiredBaseUserControl
	{
		protected override void PreLoadHandler(object sender, EventArgs e)
		{
			base.PreLoadHandler(sender, e);

			ClientScriptManager cs = Page.ClientScript;
			cs.RegisterOnSubmitStatement(this.GetType(), "onsubmit", "return ValidateIdealAmount('" + this.tbAmount.TextBox.ClientID + "');");
		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
			this.HandlePayment();
		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.Populate();
		}

		private void Populate()
		{
			this.tbAmount.TextBox.Width = Unit.Pixel(64);
			this.tbAmount.TextBox.MaxLength = 7;

			this.tbAmount.TextBox.Text = "100,00";

			IdealBanks ideal = new IdealBanks("160831");

			BankCollection banks = ideal.Banks;

			foreach (Bank bank in banks)
			{
				this.DropDownList1.Items.Add(new ListItem(bank.Name, bank.Id));
			}
		}

		private void HandlePayment()
		{
			decimal amount = decimal.Parse(this.tbAmount.TextBox.Text);
			if (amount < 0 || amount > 99999)
				this.Response.Redirect("/UI/Forms/LogOut.aspx", true);

			decimal amount10 = amount * 100;
			amount10 += 129; //€ 1,29 kosten

			string bankid = this.DropDownList1.SelectedValue;// this.Request["targetpayBankSelect"];

			IdealFetch idealFetch = new IdealFetch
				(
					"57429"
					, this.UserInfo.Gebruikersnaam + ", AandelenDelen"
					, "http://www.aandelendelen.nl/IdealCheckHandler.aspx"
					, "http://www.aandelendelen.nl/IdealTargetPayReturnHandler.aspx"
					, bankid
					, amount10
				);

			if (idealFetch.Error == false)
			{
				QueryArguments args = new QueryArguments();

				args.Add("nawid", this.UserInfo.Id, OleDbType.Integer);
				args.Add("transactionid", idealFetch.TransactionId, OleDbType.Char);
				args.Add("amount", amount, OleDbType.Currency);

				Query query = new Query("sp_insertmicropayment", args);

				query.Execute();

				this.Response.Redirect(idealFetch.Url, true);
			}
			else
			{
				this.Panel1.Visible = false;
				this.ErrorPanel.Visible = true;
			}
		}
	}
}